<?php

namespace Ignus\View\TokenParser;

use Ignus\View\TokenParser;
use Ignus\View\Error\Syntax;
use Ignus\View\Token;

class Block extends TokenParser
{
    public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();
        $name = $stream->expect(Token::NAME_TYPE)->getValue();
        if ($this->parser->hasBlock($name)) {
            throw new Syntax("The block '$name' has already been defined", $lineno);
        }
        $this->parser->pushLocalScope();
        $this->parser->pushBlockStack($name);

        if ($stream->test(Token::BLOCK_END_TYPE)) {
            $stream->next();

            $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
            if ($stream->test(Token::NAME_TYPE)) {
                $value = $stream->next()->getValue();

                if ($value != $name) {
                    throw new Syntax(sprintf("Expected endblock for block '$name' (but %s given)", $value), $lineno);
                }
            }
        } else {
            $body = new \Ignus\View\Node(array(
                new \Ignus\View\Node\PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno),
            ));
        }
        $stream->expect(Token::BLOCK_END_TYPE);

        $block = new \Ignus\View\Node\Block($name, $body, $lineno);
        $this->parser->setBlock($name, $block);
        $this->parser->popBlockStack();
        $this->parser->popLocalScope();

        return new \Ignus\View\Node\BlockReference($name, $lineno, $this->getTag());
    }

    public function decideBlockEnd(Token $token)
    {
        return $token->test('endblock');
    }

    public function getTag()
    {
        return 'block';
    }
}
